import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
import 'dart:async';

class InlineVideoPlayer extends StatefulWidget {
  final File videoFile;

  const InlineVideoPlayer({
    super.key,
    required this.videoFile,
  });

  @override
  State<InlineVideoPlayer> createState() => _InlineVideoPlayerState();
}

class _InlineVideoPlayerState extends State<InlineVideoPlayer> {
  VideoPlayerController? _controller;
  bool _isPlaying = false;
  bool _isInitialized = false;
  String? _errorMessage;
  bool _showControls = true;
  Timer? _hideControlsTimer;

  @override
  void initState() {
    super.initState();
    _initializeVideoPlayer();
  }

  Future<void> _initializeVideoPlayer() async {
    try {
      setState(() {
        _errorMessage = null;
        _isInitialized = false;
      });

      print('初始化视频播放器: ${widget.videoFile.path}');
      
      if (!await widget.videoFile.exists()) {
        throw Exception('视频文件不存在');
      }
      
      final fileSize = await widget.videoFile.length();
      final fileSizeMB = (fileSize / 1024 / 1024);
      print('视频文件大小: ${fileSizeMB.toStringAsFixed(2)} MB');

      if (fileSize == 0) {
        throw Exception('视频文件为空');
      }

      // 检查文件扩展名
      final extension = widget.videoFile.path.toLowerCase().split('.').last;
      print('视频格式: $extension');

      // 清理之前的控制器
      await _disposeController();

      print('创建VideoPlayerController...');
      // 创建新控制器
      _controller = VideoPlayerController.file(widget.videoFile);
      
      _controller!.addListener(_videoListener);
      
      print('开始初始化...');
      
      // 使用较长的超时时间，但提供进度反馈
      final initializeFuture = _controller!.initialize();
      
      // 等待初始化完成，带超时
      await initializeFuture.timeout(
        const Duration(seconds: 60), // 增加到60秒
        onTimeout: () {
          throw Exception('视频初始化超时');
        },
      );
      
      print('设置播放选项...');
      await _controller!.setLooping(false);
      await _controller!.setVolume(1.0);
      
      if (mounted) {
        setState(() {
          _isInitialized = true;
        });
        
        final value = _controller!.value;
        print('视频初始化完成:');
        print('- 时长: ${value.duration}');
        print('- 分辨率: ${value.size}');
        print('- 纵横比: ${value.aspectRatio}');
        print('- 是否有错误: ${value.hasError}');
        if (value.hasError) {
          print('- 错误信息: ${value.errorDescription}');
        }
      }

    } catch (e) {
      print('视频初始化失败: $e');
      if (mounted) {
        setState(() {
          String errorMsg = '视频播放失败';
          final errorStr = e.toString().toLowerCase();
          
          if (errorStr.contains('timeout')) {
            errorMsg += '\n\n原因: 初始化超时';
            errorMsg += '\n\n建议: 视频文件过大或损坏';
          } else if (errorStr.contains('codec') || errorStr.contains('format') || 
                     errorStr.contains('unsupported')) {
            errorMsg += '\n\n原因: 不支持的视频格式';
            errorMsg += '\n\n支持的格式: MP4, MOV, AVI';
          } else if (errorStr.contains('permission') || errorStr.contains('access')) {
            errorMsg += '\n\n原因: 文件访问权限问题';
            errorMsg += '\n\n建议: 重新选择目录';
          } else if (errorStr.contains('avfoundation') || errorStr.contains('avplayer')) {
            errorMsg += '\n\n原因: macOS视频引擎问题';
            errorMsg += '\n\n建议: 尝试重启应用';
          } else {
            errorMsg += '\n\n详细信息: $e';
          }
          
          _errorMessage = errorMsg;
        });
      }
    }
  }

  Future<void> _disposeController() async {
    _controller?.removeListener(_videoListener);
    await _controller?.pause();
    _controller?.dispose();
    _controller = null;
  }

  void _videoListener() {
    if (mounted && _controller != null) {
      final wasPlaying = _isPlaying;
      final isPlaying = _controller!.value.isPlaying;
      
      if (wasPlaying != isPlaying) {
        setState(() {
          _isPlaying = isPlaying;
        });
      }
    }
  }

  void _togglePlayPause() {
    if (_controller == null || !_isInitialized) return;

    if (_controller!.value.isPlaying) {
      _controller!.pause();
    } else {
      _controller!.play();
    }
    
    _showControlsTemporarily();
  }

  void _showControlsTemporarily() {
    setState(() {
      _showControls = true;
    });
    
    _hideControlsTimer?.cancel();
    _hideControlsTimer = Timer(const Duration(seconds: 3), () {
      if (mounted && _isPlaying) {
        setState(() {
          _showControls = false;
        });
      }
    });
  }

  void _toggleControls() {
    setState(() {
      _showControls = !_showControls;
    });
    
    if (_showControls && _isPlaying) {
      _showControlsTemporarily();
    }
  }


  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return '$minutes:$seconds';
  }

  @override
  void dispose() {
    _hideControlsTimer?.cancel();
    _disposeController();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_errorMessage != null) {
      return Container(
        color: Colors.black,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(
                Icons.error_outline,
                color: Colors.white54,
                size: 64,
              ),
              const SizedBox(height: 16),
              const Text(
                '视频播放失败',
                style: TextStyle(color: Colors.white, fontSize: 18),
              ),
              const SizedBox(height: 8),
              Padding(
                padding: const EdgeInsets.all(16),
                child: Text(
                  _errorMessage!,
                  style: const TextStyle(color: Colors.white70, fontSize: 14),
                  textAlign: TextAlign.center,
                ),
              ),
              const SizedBox(height: 16),
              ElevatedButton.icon(
                onPressed: _initializeVideoPlayer,
                icon: const Icon(Icons.refresh),
                label: const Text('重试'),
              ),
            ],
          ),
        ),
      );
    }

    if (!_isInitialized || _controller == null) {
      return Container(
        color: Colors.black,
        child: const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(color: Colors.white),
              SizedBox(height: 16),
              Text(
                '正在加载视频...',
                style: TextStyle(color: Colors.white70),
              ),
            ],
          ),
        ),
      );
    }

    return Container(
      color: Colors.black,
      child: GestureDetector(
        onTap: _toggleControls,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Center(
              child: AspectRatio(
                aspectRatio: _controller!.value.aspectRatio,
                child: VideoPlayer(_controller!),
              ),
            ),
            if (_showControls || !_isPlaying)
              GestureDetector(
                onTap: _togglePlayPause,
                child: Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    color: Colors.black.withValues(alpha: 0.5),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    _isPlaying ? Icons.pause : Icons.play_arrow,
                    size: 40,
                    color: Colors.white,
                  ),
                ),
              ),
            if (_showControls)
              Positioned(
                bottom: 20,
                left: 20,
                right: 20,
                child: Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.black.withValues(alpha: 0.8),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: ValueListenableBuilder<VideoPlayerValue>(
                    valueListenable: _controller!,
                    builder: (context, value, child) {
                      return Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SliderTheme(
                            data: SliderTheme.of(context).copyWith(
                              activeTrackColor: Colors.white,
                              inactiveTrackColor: Colors.white30,
                              thumbColor: Colors.white,
                              overlayColor: Colors.white.withValues(alpha: 0.2),
                              thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 8),
                              trackHeight: 3,
                            ),
                            child: Slider(
                              value: value.position.inMilliseconds.toDouble().clamp(
                                0.0,
                                value.duration.inMilliseconds.toDouble(),
                              ),
                              max: value.duration.inMilliseconds.toDouble(),
                              onChanged: (newValue) {
                                _controller!.seekTo(Duration(milliseconds: newValue.toInt()));
                              },
                            ),
                          ),
                          const SizedBox(height: 8),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                _formatDuration(value.position),
                                style: const TextStyle(color: Colors.white, fontSize: 14),
                              ),
                              Text(
                                _formatDuration(value.duration),
                                style: const TextStyle(color: Colors.white, fontSize: 14),
                              ),
                            ],
                          ),
                        ],
                      );
                    },
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}